package cn.xsshome.imagetool.util;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * Description 无损操作图片
 * ProjectName imagetool
 * Created by 小帅丶 on 2022-04-18
 * Version 1.0
 */

public class ImageLossLessUtil {

    /**
     * @Author 小帅丶
     * @Description 把图片无损再次保存
     * @Date  2022/4/18 13:48
     * @param sourceImgPath - 原始文件路径
     * @param targetImgPath - 目标文件路径
     * @param suffix - 文件格式
     * @return void
     **/
    public static void saveLossLessImage(String sourceImgPath,String targetImgPath,String suffix) throws Exception{
        BufferedImage image = ImageIO.read(new File(sourceImgPath));
        saveLossLessImage(image,targetImgPath,suffix);
    }

    /**
     * @Author 小帅丶
     * @Description 把图片无损再次保存
     * @Date  2022/4/18 13:48
     * @param image -  BufferedImage对象
     * @param targetImgPath - 目标文件路径
     * @param suffix - 文件格式
     * @return void
     **/
    public static void saveLossLessImage(BufferedImage image,String targetImgPath,String suffix) throws Exception{
        //不压缩图片质量进行保存
        ImageWriter writer = ImageIO.getImageWritersBySuffix(suffix).next();
        ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        //0-1范围 越大质量越高
        imageWriteParam.setCompressionQuality(1);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(output));
        writer.write(null,new IIOImage(image,null,null),imageWriteParam);
        writer.dispose();
        //最终图片保存路径
        FileOutputStream file = new FileOutputStream(targetImgPath);
        file.write(output.toByteArray());
        file.close();
        output.close();
    }

}
